package com.learning.test.config;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
public class DataSourceConfig {
  @Autowired
  private Environment environment; // 用于获取application.properties中的属性值
  
  private final String DS_DRIVER = "spring.datasource.driver-class-name";
  private final String DS_URL = "spring.datasource.url";
  private final String DS_USERNAME = "spring.datasource.username";
  private final String DS_PASSWORD = "spring.datasource.password";
  
  @Bean
  DataSource dataSource() {
    DataSourceBuilder<?> dsb = DataSourceBuilder.create();
    dsb.driverClassName(environment.getProperty(DS_DRIVER));
    dsb.url(environment.getProperty(DS_URL));
    dsb.username(environment.getProperty(DS_USERNAME));
    dsb.password(environment.getProperty(DS_PASSWORD));
    dsb.type(BasicDataSource.class);
    return dsb.build();
  }
}
